package com.mqtt.demo1.config;

import com.mqtt.demo1.properties.MqttProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * 参考文档：https://juejin.cn/post/6953134217547120654
 *  https://juejin.cn/post/7008123266023817253
 */
@Slf4j
@Component
public class MqttConfiguration {

    @Autowired
    private MqttProperties mqttProperties;

    /**
     * 初始化客户端链接
     * @return
     */
    @SneakyThrows
    @Bean
    public MqttClient mqttClient() {
        MqttClient mqttClient = new MqttClient(mqttProperties.getBroker(), mqttProperties.getClientId(), new MemoryPersistence());
        // 配置连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        // 配置用户名和密码
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        // 是否清空session，设置为false表示服务器会保留客户端的连接记录，客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
        // 设置为true表示每次连接到服务端都是以新的身份
        options.setCleanSession(true);
        // 设置自动重连
        options.setAutomaticReconnect(true);
        options.setKeepAliveInterval(7);
        options.setMaxInflight(1000);
        options.setConnectionTimeout(3);
        if (!mqttClient.isConnected()) {
            mqttClient.connect(options);
        }
        return mqttClient;
    }


}
